const cheerio = require("cheerio");
const prettier = require("prettier");
const fse = require("fs-extra");
const path = require("path");
const glob = require("glob");

function generate(filePath) {
  var text = fse.readFileSync(filePath, "utf8");

  text = prettier.format(text, { semi: false, parser: "html" });

  const $ = cheerio.load(text, { decodeEntities: false });

  var dataFiles = $("[data-file]");
  for (let i = dataFiles.length; i > 0; i--) {
    var v = dataFiles[i - 1];
    var file = $(v).attr("data-file");
    $(v).removeAttr("data-file");
    var parentDir = path.join("../template", path.dirname(file));
    if (!fse.existsSync(parentDir)) {
      fse.mkdirpSync(parentDir);
    }
    var html = cheerio.html($(v));
    var f = path.join("../template", file);

    fse.writeFileSync(f, html, "utf8");
    console.log(f);
    $(v).replaceWith('{{include "' + file + '" . }}');
  }

  fse.writeFileSync("../template/" + path.basename(filePath), $.html(), "utf8");
}

glob("./dist/*.html", function (err, files) {
  if (err) {
    console.log(err);
  } else {
    files.forEach((file) => {
      if (file.indexOf("app.html") > -1) {
        return true;
      }
      generate(file);
    });
  }
});
